<template>
  <div class="app-container course-add course width-label">
    <div class="edit-title-line">基本信息</div>
    <el-form ref="addCourseForm" :model="addCourseForm" :rules="addCourseFormRules" >
      <div>
        <el-form-item label="标题：" class="normal-form-item" prop="title" >
          <el-input v-model="addCourseForm.title" class="width-300" size="small"
           @focus="clearFormValidate('title')"
           ref="title"
          ></el-input>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="类型：" class="normal-form-item" prop="courseType">
          <el-select v-model="addCourseForm.courseType" placeholder="请选择" class="width-300"  size="small" clearable >
            <el-option
              v-for="item in courseTypeData"
              :key="item.code"
              :label="item.label"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="学期：" class="normal-form-item"  prop="semesterCode">
          <el-select v-model="addCourseForm.semesterCode"
                     placeholder="请选择" class="width-300"
                     size="small"
                     @change="handleChangeSemester"
                     clearable >
            <el-option
              v-for="item in schoolSemesterList"
              :key="item.code"
              :label="item.label"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="学科：" class="normal-form-item" prop="subjectName">
          <el-select v-model="addCourseForm.subjectName" @change="handleSubjectChange" placeholder="请选择" class="width-300"  size="small"  clearable >
            <el-option
              v-for="item in subjectTypeData"
              :key="item.subjectName"
              :label="item.subjectName"
              :value="item.subjectName">
            </el-option>
          </el-select>
        </el-form-item>
  </div>
      <div>
        <el-form-item label="年级：" class="normal-form-item" prop="gradeType">
          <el-select v-model="addCourseForm.gradeType" placeholder="请选择" class="width-300" @change="handleGradeChange(false)" size="small" clearable >
            <el-option
              v-for="item in gradeTypeData"
              :key="item.distanceYear"
              :label="item.name"
              :value="item.distanceYear">
            </el-option>
          </el-select>
        </el-form-item>
      </div>

      <div>
        <el-form-item label="班级：" class="normal-form-item" prop="classData">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAllClass" @change="handleCheckAllClassChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="addCourseForm.classData" @change="handleCheckedClassChange">
            <el-checkbox v-for="(classItem, index) in classData"
                         :label="classItem.classId"
                         :key="classItem.classId">{{classItem.className}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </div>

      <div class="edit-title-line">附件</div>
      <el-upload
        style="display: block"
        class="upload-demo course-add-file"
        ref="batchUpload"
        name="files"
        :action="fileUploadUrl"
        :accept="acceptFileType"
        :before-upload="beforeFileUpload"
        :on-success="handleFileUploadSuccess"
        :on-change="uploadFileListChange"
        :on-remove="handleUploadFileRemove"
        :file-list="uploadFileList"
      >
        <div class="batchUpload-button" style="margin-bottom: 10px" v-if="showUploadTip">
          <el-button slot="trigger" size="small" type="primary" >添加附件</el-button>
        </div>
        <div slot="tip"  class="el-upload__tip" v-if="showUploadTip">最大可上传不超过20M的文档，最多可上传3个文件，支持word、excel、PPT、图片。</div>
      </el-upload>
      <div class="course-detail-annex-list">
        <div class="annex-list-item" v-for="(item, index) in addCourseForm.annexList" :key="index">
          <div class="annex-list-item-index">{{index+1}}</div>
          <div class="annex-list-item-annexName">{{item.fileName}}</div>
          <div class="annex-list-item-delete" @click="deleteAnnex(index)">删除</div>
        </div>
      </div>
      <div class="edit-title-line">备课内容</div>
      <div>
        <editor-bar v-model="addCourseForm.courseContent.editor" :height="600" ></editor-bar>
      </div>
      <div style="margin-top: 20px">
        <el-form-item>
          <el-button type="primary" style="margin-right: 20px" @click="addCourseFormSubConfirm">保存</el-button>
          <el-button @click="cancelConfirm=true">取消</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-confirm-dialog
      elTip="确定要取消吗，若取消当前信息将不会保存？"
      :showDialog="cancelConfirm"
      :confirmSubmit="elConfirmDialogSubmit"
      :confirmCancel="elConfirmDialogCancel"
      @closeDialog = "elConfirmDialogClose"
    >
    </el-confirm-dialog>
  </div>
</template>

<script>
  import ElConfirmDialog from '@/components/ElConfirmDialog/index.vue'
  import EditorBar from '@/components/Tinymce'
  import {getPlLessonDetail, getSubjectList, getSchoolGradeList,
    getSchoolSemesterList, getSchoolClassList, saveOrUpdatePLesson} from '@/api/api.js'
  import {getCurrentSemesterTerm} from '@/utils/utils.js'
  import {mapGetters} from 'vuex'

  export default {
    name: "courseEdit",
    components: {
      ElConfirmDialog,
      EditorBar
    },
    computed: {
      ...mapGetters([
        'userInfo'
      ])
    },
    data() {
      return {
        fileUploadUrl: `${process.env.VUE_APP_BASE_API}/busi/upload/file?code=6`,
        //文件上传类型
        acceptFileType: ".xls, .xlsx, .ppt, .pptx, .doc, .docx, image/*",
        fileType: [
          'gif',
          'jpeg',
          'jpg',
          'bmp',
          'png',
          'ppt',
          'pptx',
          'doc',
          'docx',
          'xls',
          'xlsx'
        ],
        //班级列表
        classData: [],
        //班级全选
        checkAllClass: false,
        isIndeterminate: false,
        //年级类型
        gradeTypeData: [],
        // 学科类型
        subjectTypeData: [],
        //备课类型
        courseTypeData: [
          {code: 1, label: "教案"},
          {code: 2, label: "单元测试分析"},
          {code: 3, label: "单元教学分析"},
          {code: 4, label: "教学计划及进度"},
        ],
        //当前学科
        currentSubject: {
          subjectId: '',
          subjectName : '',
          subjectCode : '',
          subjectType : '',
          subjectLevel : '',
        },
        // 当前学年
        currentSemester: {
          semesterId : '',
          schoolYear : '',
          term: '',
        },
        //当前年级
        currentGrade: {
          gradeName: '',
          distanceYear: '',
        },
        schoolSemesterList: [],
        addCourseForm: {
          id: '',
          title: '',
          courseType: '',
          subjectType: '',
          subjectName: '',
          gradeType: '',
          semesterCode: '',
          annexList: [],
          classData: [],
          prepareLessons: '', //备课内容,
          courseContent: {
            editor: '',
            isClear : false,
          }
        },
        addCourseFormRules: {
          title : [
            { required: true, message: '必填项，请填写！', trigger: 'blur' },
            { max: 30, message: '最多 30 个字符', trigger: 'blur' }
          ],
          courseType: [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],
          subjectName : [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],
          gradeType : [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],
          classData: [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],

          semesterCode : [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ]
        },
        // 文件上传列表
        uploadFileList: [],

        //询问框
        cancelConfirm: false,
        //显示上传按钮
        showUploadTip : true,
        phpGradeList: [],
        classIdList : [],
      }
    },
    methods: {
      // 班级全选
      handleCheckAllClassChange(val) {
        if(val) {
          this.addCourseForm.classData = this.classData.map(item => {
            return item.classId
          })
        } else {
          this.addCourseForm.classData = []
        }
        this.isIndeterminate = false;
      },
      // 班级checkBox变化
      handleCheckedClassChange(value)  {

        let checkedCount = value.length;
        this.checkAllClass = checkedCount === this.classData.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.classData.length;
      },
      //根据班级id详情
      getClassDetailById(id) {
        for (let item of this.classData) {
          if (item.classId == id) {
            return item
          }
        }
        return null
      },
      JSONStringifyClassList(classArr) {
        let resArr = []
        classArr.forEach(classId => {
          let tempClassDetail = this.getClassDetailById(classId)
          if (tempClassDetail) {
            resArr.push(tempClassDetail)
          }
        })
        return JSON.stringify(resArr)
      },
      //年级变化获取对应的班级
       handleGradeChange(initClass) {
        if (!initClass) {
          this.addCourseForm.classData = []
          // this.$nextTick(() => {
          //   this.clearFormValidate('gradeType')
          // })
        }
        this.classData = []
        this.isIndeterminate = false
        this.checkAllClass = false
        let tempGrade = this.getGradeMsgByDistanceYear(this.addCourseForm.gradeType);
        if (tempGrade == null) {
          this.classData = []
          return ;
        }
        this.currentGrade.distanceYear = tempGrade.distanceYear;
        this.currentGrade.gradeName = tempGrade.name;
        let params = {
          grade : tempGrade.name,
          distanceYear: tempGrade.distanceYear
        }
        getSchoolClassList(params).then(res => {
          if (res.code == 200) {
            // this.classData = res.result || []
            this.isIndeterminate = false
            if (initClass) {
              this.formatIndeterminate()
            }
            for (let tempClass of res.result) {
              for (let phpGrade of this.phpGradeList) {
                if (phpGrade.classId == tempClass.classId && this.currentGrade.distanceYear == tempClass.distanceYear) {
                  this.classData.push(tempClass)
                }
              }
            }
          } else {
            this.$alert('学校还未维护该年级下班级  信息，请联系华育技术支持进行初始化！', '提示', {
              confirmButtonText: '我知道了',
            });
          }
        })
      },
      /** 附件上传相关 **/
      beforeFileUpload(file, fileList) {
        if (this.addCourseForm.annexList.length >= 3) {
          this.$message.warning("很抱歉，最多只能上传3个附件！")
          return false;
        }
      },
      handleFileUploadSuccess(res, file) {
        let tempSort = this.addCourseForm.annexList.length == 0 ? 0 : this.addCourseForm.annexList.length
       let itemFile = {
         fileName : res.result[0].fileName,
         filePath : res.result[0].filePath,
         sort : tempSort,
       }
       this.addCourseForm.annexList.push(itemFile)
        this.addCourseForm.annexList.forEach((item, index) => item.sort = index)
      },
      uploadFileListChange(file, fileList) {
        if (!this.validateFileType(file)) {
          this.$message.warning("暂不支持此类文件上传！")
          fileList.pop();
          return  false;
        }
        if (!this.validateFileSize(file)) {
          this.$message.warning("单个文件最大可上传20M，请重新上传！")
          fileList.pop()
          return  false;
        }
        if (this.addCourseForm.annexList.length >= 4) {
          this.$message.warning("很抱歉，最多只能上传3个附件！")
          fileList.pop()
          return false;
        }
        //过滤重复文件
        let filterFileList =  fileList.filter((fileItem, index, self) => {
          //存放文件名称的数组
          let fileNameList = []
          fileList.forEach(fileTemp => {
            if(fileTemp.name != undefined) {
              fileNameList.push(fileTemp.name);
            }
          })
          return fileNameList.indexOf(fileItem.name) === index ;
        })
        this.uploadFileList = filterFileList
      },
      handleUploadFileRemove(file, fileList) {

      },
      //校验文件类型
      validateFileType(file) {
        if (file.name != undefined) {
          let type = file.name.substring(file.name.lastIndexOf(".")+1)
          return this.fileType.indexOf(type) !== -1 ? true : false
        }
      },
      //校验文件大小 小于等于 20M
      validateFileSize(file) {
        if (file.size != undefined) {
          return   file.size / 1024 / 1024 < 20 ? true : false
        }
      },
      //文件删除
      deleteAnnex(index) {
        if (index > this.addCourseForm.annexList.length) {
          return ;
        }
        this.addCourseForm.annexList.splice(index, 1);
        if (this.addCourseForm.annexList.length > 0) {
          this.addCourseForm.annexList.forEach((item, index) => {
            item.sort = index
          })
        }
        this.showUploadTip = true
      },
      /** 文件上传结束**/

      /** 取消询问框相关**/
      elConfirmDialogSubmit() {
        this.initAddCourseForm()
        this.$router.push("/personal/courseList")
      },
      elConfirmDialogCancel() {
        this.cancelConfirm = false
      },
      elConfirmDialogClose() {
        this.cancelConfirm = false
      },

      /** 表单提交相关 **/
      addCourseFormSubConfirm() {
        this.$refs.addCourseForm.validate(valid => {
          if (valid) {
            // this.uploadFileList 文件上传列表
            let params = {
              id : this.addCourseForm.id,
              title : this.addCourseForm.title,
              type :this.addCourseForm.courseType,
              content : this.addCourseForm.courseContent.editor,
              semesterId : this.currentSemester.semesterId,
              term : this.currentSemester.term,
              schoolYear: this.currentSemester.schoolYear,
              subjectType : this.addCourseForm.subjectType,
              subjectId : this.currentSubject.subjectId,
              subjectName : this.currentSubject.subjectName,
              subjectCode : this.currentSubject.subjectCode,
              subjectLevel : this.currentSubject.subjectLevel,
              grade : this.addCourseForm.gradeType,
              anndexList : JSON.stringify(this.addCourseForm.annexList), //附件列表
              classList : this.JSONStringifyClassList(this.addCourseForm.classData)
            }
            saveOrUpdatePLesson(params).then(res => {
              if (res.code === 200) {
                this.$alert("保存成功！", "提示", {type : "success",
                  callback : () => {
                    this.$router.push({path : "/personal/courseList"})
                  }
                })
              } else {
                this.$alert("保存失败！" + res.message, "错误", {type : "error"})
              }
            })
          } else {
            this.$alert("输入有误，请检查", "提示", {type : "warning"})
          }
        })
      },
      //表单初始化
      initAddCourseForm() {
        //缺少富文本字段
        this.addCourseForm = {
          title: '',
          courseType: '',
          subjectType: '',
          gradeType: '',
          annexList: [],
          classData: [],
        }
      },
      /**  初始化  **/
      //获取备课详情
      getCourseDetail() {
        let plLessonId = this.$route.query.courseId
        if(!plLessonId) {
          this.$router.go(-1)
        }
        let params  = {
          plLessonId : plLessonId
        }
        getPlLessonDetail(params).then(res => {
          if (res.code == 200) {
            this.addCourseForm.id = res.result.id
            this.addCourseForm.title = res.result.title
            this.addCourseForm.courseType = res.result.type
            this.addCourseForm.subjectType = res.result.subjectId
            this.addCourseForm.subjectName = res.result.subjectName
            this.addCourseForm.gradeType = res.result.classList[0].distanceYear
            this.addCourseForm.annexList = res.result.anndexList
            this.addCourseForm.courseContent.editor = res.result.content || null
            this.addCourseForm.semesterCode = `${res.result.schoolYear}${res.result.term}`
            this.classIdList = res.result.classList
            this.formatAnnexList(res.result.anndexList)
            this.initGradeList()
            this.initCurrentSubject(res.result.subjectId, res.result.subjectName)
            this.initCurrentSemester(this.addCourseForm.semesterCode)

            if (res.result && res.result.anndexList && res.result.anndexList.length >= 3) {
              // 附件超过三个不显示上传按钮和提示
              this.showUploadTip = false
            }
          } else {
            this.$alert("获取备课数据失败！" + res.message, "错误", {type : "error"})
          }
        })
      },
      //初始化当前学科信息
      initCurrentSubject(subjectId, subjectName) {
        if ( this.subjectTypeData.length <= 0) {
          return null;
        }
        for (let item of this.subjectTypeData) {
          if (item.subjectName == subjectName) {
            this.currentSubject.subjectId = item.subjectId
            this.currentSubject.subjectLevel = item.subjectLevel
            this.currentSubject.subjectType = item.subjectType
            this.currentSubject.subjectCode = item.subjectCode
            this.currentSubject.subjectName = item.subjectName
            break
          }
        }
        for (let item of this.subjectTypeData ) {
          if(item.subjectId == subjectId) {
            this.currentSubject.subjectId = item.subjectId
            this.currentSubject.subjectLevel = item.subjectLevel
            this.currentSubject.subjectType = item.subjectType
            this.currentSubject.subjectCode = item.subjectCode
            this.currentSubject.subjectName = item.subjectName
            break;
          }
        }
      },
      // 初始化科目信息
      initSubjectList() {
        let params = {
        }
        getSubjectList(params).then(res => {
          if(res.code == 200) {
            this.subjectTypeData = this.formatSubjectList(res.result)
          } else {
            this.$alert("获取学科数据失败！" + res.message, "错误", {type : "error"})
          }
        })
      },
      // 格式化科目信息
      formatSubjectList(array) {
        if(!array || !Array.isArray(array) || array.length <= 0) {
          this.$alert('学校还未维护学科选项信息，请联系华育技术支持进行初始化！', '提示', {
            confirmButtonText: '我知道了',
          });
          return []
        }
        let tempArr = []
        array.forEach(item => {
          let tempItem = {
            subjectId: item.id,
            subjectName : item.name,
            subjectCode : item.code,
            subjectType : item.type,
            subjectLevel :  item.level
          }
          tempArr.push(tempItem)
        })
        return tempArr
      },
      //学科变化获取当前学科详情
      handleSubjectChange() {
        if ( this.subjectTypeData.length <= 0) {
          return null;
        }
        for (let item of this.subjectTypeData) {
          if (item.subjectName == this.addCourseForm.subjectName) {
            this.currentSubject = item
            this.$nextTick(() => {
              this.clearFormValidate('subjectName')
            })
          }
        }

      },
      //初始化年级信息
      initGradeList() {
        this.gradeTypeData= []
        getSchoolGradeList().then(res => {
          if (res.code === 200) {
            if (res.result && res.result.length && res.result.length > 0) {
              let schoolGradeList   = res.result
              let school_id = sessionStorage.getItem("schoolId")
              let user_id = this.userInfo.id
              this.$axios.get(`${process.env.VUE_APP_TDK_API}/api/classes/schedules/getTeachClassesByUserId?user_id=${user_id}&school_id=${school_id}`).then(res => {
                if  (res.data.code == 200) {

                  res.data.data = [
                    {
                      distanceYear : 4,
                      classId : '3c8ea97f5b5fa072ad45959426ff3f8acfcbe356'
                    },
                    {
                      distanceYear : 0,
                      classId : '49d0b48f19e54b84a3c2fbca833b54a2'
                    },
                    {
                      distanceYear: 0,
                      classId : '2d1133e420474cf5be7ee654f7d2e5d4'
                    }


                  ]

                  let tempGradeList =  res.data.data
                  this.phpGradeList = res.data.data
                  if (tempGradeList && Array.isArray(tempGradeList) && tempGradeList.length > 0) {
                    let distanceYearList = []
                    // 去重年级
                    tempGradeList.forEach(item => distanceYearList.push(item.distanceYear ))
                    let  filterDistanceList =    Array.from(new Set([...distanceYearList]))
                    for (let gradeItem of schoolGradeList) {
                      for (let gradeCode of filterDistanceList) {
                        if (gradeItem.distanceYear == gradeCode) {
                          this.gradeTypeData.push(gradeItem)
                        }
                      }
                    }
                  }
                  // console.log(this.addCourseForm.gradeType)
                  let params = {
                    grade : this.currentSemester.schoolYear,
                    distanceYear : this.addCourseForm.gradeType
                  }

                  getSchoolClassList(params).then(res => {
                    if (res.code == 200) {
                      this.classData = []
                      this.isIndeterminate = false
                        this.formatIndeterminate()
                      for (let tempClass of res.result) {
                        for (let phpGrade of this.phpGradeList) {
                          if (phpGrade.classId == tempClass.classId && this.addCourseForm.gradeType == tempClass.distanceYear) {
                            this.classData.push(tempClass)
                          }
                        }
                      }
                      if (this.classData.length == this.classIdList.length ) {
                        this.checkAllClass = true
                        this.isIndeterminate = false
                      } else {
                        this.checkAllClass = false
                        this.isIndeterminate = true
                      }

                      // console.log("this.currentGrade.distanceYear", this.currentGrade.distanceYear)
                      //
                      // console.log(this.classData)
                    } else {
                      this.$alert('学校还未维护该年级下班级  信息，请联系华育技术支持进行初始化！', '提示', {
                        confirmButtonText: '我知道了',
                      });
                    }
                  })
                  this.initAddFormCheckedClass( this.classIdList)
                } else {
                  this.gradeTypeData = []
                }
              })

            } else {
              this.$alert('学校还未维护年级选项信息，请联系华育技术支持进行初始化！', '提示', {
                confirmButtonText: '我知道了',
              });
            }
          } else {
            this.$alert("获取年级选项列表失败！" + res.message, "错误", {type : "error"})
          }
        })
      },
      //根据distanceYear获取学年详情
      getGradeMsgByDistanceYear(distanceYear) {
        console.log("this.gradeTypeDatalength", this.gradeTypeData.length)
        if (this.gradeTypeData && this.gradeTypeData.length && this.gradeTypeData.length > 0) {
          for (let item of this.gradeTypeData) {
            if (item.distanceYear == distanceYear) {
              return item;
            }
          }
        }
        return null;
      },
      //获取当前学年学期信息
      handleCurrentSemester: function () {
        getSchoolSemesterList().then(res => {
          if (res.code === 200) {
            if (!res.result || !Array.isArray(res.result) || res.result.length <= 0) {
              this.$alert('学校还未维护学年学期信息，请联系华育技术支持进行添加！', '提示', {
                confirmButtonText: '我知道了',
              });
              return
            } else {
              this.schoolSemesterList = res.result;
              let schoolSemester = getCurrentSemesterTerm()
              this.currentSemester.schoolYear = schoolSemester[0]
              this.currentSemester.term = schoolSemester[1]
              let currentSemesterItem =  this.schoolSemesterList.filter(item => item.schoolYear == this.currentSemester.schoolYear && item.term == this.currentSemester.term)
              if(currentSemesterItem.length <= 0) {
                this.$alert('学校还未维护当前学年学期信息，请联系华育技术支持进行初始化！', '提示', {
                  confirmButtonText: '我知道了',
                });
              }
              this.currentSemester.semesterId = currentSemesterItem[0].id
            }
          } else {
            this.$alert("获取学年学期数据失败！" + res.message, "错误", {type: "error"})
          }
        });
      },
      //初始化默认选中的班级
      initClassList() {
        this.handleGradeChange(true)
      },
      //初始化表单中选中的班级
      initAddFormCheckedClass(classArr) {
        if (classArr && Array.isArray(classArr) && classArr.length > 0) {
          classArr.forEach(item => {
            this.addCourseForm.classData.push(item.classId)
          })
        }
      },
      formatIndeterminate() {
        // this.isIndeterminate = true
        if (this.classData.length == this.addCourseForm.classData.length ) {
          this.checkAllClass = true
          this.isIndeterminate = false
        } else {
          this.checkAllClass = false
          this.isIndeterminate = true
        }
      },
      //初始化附件
      formatAnnexList(annexList){

      },
      initCurrentSemester(semesterId) {
        if (!semesterId || this.schoolSemesterList.length <= 0) {
          return
        }

        for (let item of this.schoolSemesterList) {
          if (item.code == semesterId) {
            if (item.code.length >= 5 ) {
              this.currentSemester.semesterId = item.semesterId
              this.currentSemester.schoolYear = item.code.substr(0, 4)
              this.currentSemester.term = item.code.substr(4, 1)

            }
            break;
          }
        }
      },
      handleChangeSemester() {
        if (!this.addCourseForm.semesterCode || this.schoolSemesterList.length < 0){
          return null
        }

        for (let item of this.schoolSemesterList) {
          if (item.code == this.addCourseForm.semesterCode) {
            if (item.code.length >= 4 ) {
              this.currentSemester.semesterId = item.semesterId
              this.currentSemester.schoolYear = item.code.substr(0, 4)
              this.currentSemester.term = item.code.substr(4, 1)
            }
            break;
          }
        }
      },

      initSchoolSemester() {
        getSchoolSemesterList().then(res => {
          if ( res.code == 200) {
            if (res.result && Array.isArray(res.result) && res.result.length > 0) {
              let tempSemesterList  = res.result
              tempSemesterList.forEach(semesterItem => {
                let year = parseInt(semesterItem.schoolYear) + parseInt(1)
                let term = semesterItem.term == 1 ? "第一学期" : "第二学期"
                let label   =  `${ parseInt(semesterItem.schoolYear)}年-${year}年${term}`
                let code = `${semesterItem.schoolYear}${semesterItem.term}`
                let semesterId = semesterItem.id
                this.schoolSemesterList.push({label, code, semesterId})
              })
              this.schoolSemesterList.sort(this.compare('code'))
              this.getCourseDetail()
            } else {
              this.$alert('学校还未维护学年学期信息，请联系华育技术支持进行添加！', '提示', {
                confirmButtonText: '我知道了',
              });
            }
          } else {
            this.$alert("获取学年学期数据失败！" + res.message, "错误", {type: "error"})
          }
        })
      },
      /**清除校验**/
      clearFormValidate(prop) {
        this.$refs.addCourseForm.clearValidate(prop)
      },
      compare (propertyName) {
        return function (object1, object2) {
          let value1 = object1[propertyName]
          let value2 = object2[propertyName]
          if (value2 > value1) {
            return 1
          } else if (value2 < value1) {
            return -1
          } else {
            return 0
          }
        }
      }
      /**  初始化结束  **/
    },
    created() {
      this.initSubjectList()
      this.initSchoolSemester()
    },
    mounted() {
      this.$refs.addCourseForm.clearValidate();
      this.$refs.title.focus()
    },
  }
</script>

<style scoped lang="scss">
  .course-add {
    .el-form-item__error {
      top: 25% !important;
      right: 0 !important;
    }
  }

</style>
